package com.example.test_witns.ui.my_qrcode;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.AnimatedVectorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Size;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.AspectRatio;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.example.test_witns.R;
import com.example.test_witns.UserIntroductionActivity;
import com.example.test_witns.view.CenterThickScanLineView;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.mlkit.vision.barcode.BarcodeScanner;
import com.google.mlkit.vision.barcode.BarcodeScannerOptions;
import com.google.mlkit.vision.barcode.BarcodeScanning;
import com.google.mlkit.vision.barcode.common.Barcode;
import com.google.mlkit.vision.common.InputImage;

import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VerticalScannerActivity extends AppCompatActivity {
    private PreviewView previewView;
    private ExecutorService cameraExecutor;
    private ValueAnimator animator;
    private ImageView scanLineAnim;
    private long lastScanTime = 0;
    private static final int SCAN_INTERVAL = 1000;
    private static final int REQUEST_CODE_PERMISSIONS = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vertical_scanner);
        previewView = findViewById(R.id.preview_view);
        CenterThickScanLineView scan_line = findViewById(R.id.scan_line);

        scan_line.post(() -> {
            animator = ValueAnimator.ofFloat(0f, 1f);
            animator.addUpdateListener(animation -> {
                float progress = (float) animation.getAnimatedValue();
                scan_line.setProgress(progress);
            });
            animator.setDuration(4200);
            animator.setRepeatCount(ValueAnimator.INFINITE);
            animator.start();
        });

        Objects.requireNonNull(getSupportActionBar()).hide();
        Window window = getWindow();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        window.setStatusBarColor(Color.parseColor("#00EFFAFF"));

        ImageView qr_code_scan_back = findViewById(R.id.qr_code_scan_back);
        qr_code_scan_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        if (checkPermissions()) {
            startCamera();
        } else {
            requestPermissions();
        }
        cameraExecutor = Executors.newSingleThreadExecutor();
    }

    // ========== 摄像头控制 ==========
    private void startCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = 
            ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                
                // 预览配置
                Preview preview = new Preview.Builder()
                    .setTargetAspectRatio(AspectRatio.RATIO_4_3)
                    .build();

                // 摄像头选择（后置）
                CameraSelector cameraSelector = new CameraSelector.Builder()
                    .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                    .build();

                // 图像分析配置（用于二维码识别）
                ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
                    .setTargetResolution(new Size(1280, 720))
                    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                    .build();

                // 绑定到生命周期
                cameraProvider.bindToLifecycle(
                    (LifecycleOwner)this,
                    cameraSelector,
                    preview,
                    imageAnalysis
                );

                // 设置预览视图
                preview.setSurfaceProvider(previewView.getSurfaceProvider());
                
                // 二维码分析处理
                setupBarcodeAnalyzer(imageAnalysis);

            } catch (Exception e) {
                Toast.makeText(this, "摄像头初始化失败", Toast.LENGTH_SHORT).show();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    // ========== 二维码识别处理 ==========
    private void setupBarcodeAnalyzer(ImageAnalysis imageAnalysis) {
        BarcodeScannerOptions options = new BarcodeScannerOptions.Builder()
            .setBarcodeFormats(Barcode.FORMAT_QR_CODE)
            .build();

        BarcodeScanner scanner = BarcodeScanning.getClient(options);

        imageAnalysis.setAnalyzer(cameraExecutor, imageProxy -> {
            @SuppressLint("UnsafeOptInUsageError")
            InputImage image = InputImage.fromMediaImage(
                imageProxy.getImage(),
                imageProxy.getImageInfo().getRotationDegrees()
            );

            scanner.process(image)
                .addOnSuccessListener(barcodes -> {
                    for (Barcode barcode : barcodes) {
                        String rawValue = new String(barcode.getRawValue().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                        if (rawValue != null) {
                            // 处理扫描结果
                            handleScanResult(rawValue);
                            imageProxy.close();
                            return;
                        }
                    }
                    imageProxy.close();
                })
                .addOnFailureListener(e -> imageProxy.close());
        });
    }

    // ========== 处理扫描结果 ==========
    private void handleScanResult(String content) {
        runOnUiThread(() -> {
            long currentTime = System.currentTimeMillis();
            if (currentTime - lastScanTime < SCAN_INTERVAL) {
                return; // 忽略1秒内的重复结果
            }
            lastScanTime = currentTime;
            // 震动反馈
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(100);

            // 跳转到添加好友界面
            String[] infos = content.split(",");
            Intent intent = new Intent(this, UserIntroductionActivity.class);
            intent.putExtra("nickname", infos[0]);
            intent.putExtra("userEmail", infos[1]);
            intent.putExtra("uuid", infos[2]);
            intent.putExtra("userAvatarURL", infos[3]);
            startActivity(intent);
        });
    }

    // ========== 权限处理 ==========
    private boolean checkPermissions() {
        return ContextCompat.checkSelfPermission(
            this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermissions() {
        ActivityCompat.requestPermissions(
            this,
            new String[]{Manifest.permission.CAMERA},
            REQUEST_CODE_PERMISSIONS
        );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startCamera();
            } else {
                Toast.makeText(this, "需要相机权限", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void startScanAnimation() {
        Drawable drawable = scanLineAnim.getDrawable();
        if (drawable instanceof AnimatedVectorDrawable) {
            AnimatedVectorDrawable anim = (AnimatedVectorDrawable) drawable;
            anim.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cameraExecutor.shutdown();
    }

}